package com.tangsm.spring.boot.api.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * 请求信息获取实例
 * @author tangyb
 * @date 2022/08/09
 */
@RequestMapping("/param")
@RestController
public class ApiRequestParamController {
    private static final Logger log = LoggerFactory.getLogger(ApiRequestParamController.class);

    /**
     * 请求信息获取
     * <pre>
     * url：http://localhost:8080/api/v1/execute?name=小美&age=18
     * body:
     * {
     *   "scores": [
     *     {
     *       "course": "语文",
     *       "score": 98
     *     },
     *     {
     *       "course": "数学",
     *       "score": 92
     *     }
     *   ]
     * }
     * 注：body为json数组请求异常
     * </pre>
     * @param request 请求信息
     * @return 响应结果
     * @throws IOException IO异常
     */
    @PostMapping("/execute")
    public Object execute(HttpServletRequest request) throws IOException {
        log.info("请求信息获取开始.");
        // 获取请求主体参数
        String json = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
        log.info("获取请求主体参数：{}", json);

        // 设置request对象的解码方式
        request.setCharacterEncoding("utf-8");

        // 获取参数
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        log.info("姓名:" + name);
        log.info("年龄:" + age);

        Map<String, String[]> paramMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
            log.info("Key = " + entry.getKey() + ", Value = " + Arrays.toString(entry.getValue()));
        }

        // 获取请求方法
        String method = request.getMethod();
        log.info("获取请求方法：{}", method);

        // 获取指定header值
        String token = request.getHeader("token");
        log.info("获取指定header值，token：{}", token);

        // 获取所有header名称
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            // header名称
            String key = headerNames.nextElement();
            // header值
            String header = request.getHeader(key);

            log.info("Header名称：{}，值：{}", key, header);
        }
        return "hello";
    }
}
